#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

#define KEY_COUNT   3 

void key_process(void *avg)
{
    /*key1 key2 IR_key*/
    uint8_t key_pin[3];

    key_pin[0] = rt_pin_get("PE.0");
    key_pin[1] = rt_pin_get("PF.0");
    key_pin[2] = rt_pin_get("PF.1");

    for(uint8_t i = 0; i < KEY_COUNT; i++)
        rt_pin_mode(key_pin[i], PIN_MODE_INPUT_PULLUP);

    rt_kprintf("key init ok \n");
    
    uint16_t key_buf[KEY_COUNT];
    rt_memset(key_buf, 0xff, KEY_COUNT);
    while(true)
    {
        for(uint8_t i = 0; i < KEY_COUNT; i++)
        {
            key_buf[i] = (key_buf[i] << 1) | rt_pin_read(key_pin[i]);
            if(key_buf[i] == 0x00ff)
            {
                rt_kprintf("key%d Press \n", i);
            }
        }
        rt_thread_mdelay(10);
    }
}


static int key_process_thread_create(void)
{
    rt_thread_t key_process_thread;

    key_process_thread = rt_thread_create("key_thread", key_process, 
                                    RT_NULL, 1024, 
                                    10, 20);
    
    if (key_process_thread) 
        return rt_thread_startup(key_process_thread);
    else 
        return RT_ERROR;
}

INIT_APP_EXPORT(key_process_thread_create);
